<template>
  <div class="add">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-alert
          title="添加商品"
          show-icon
          type="warning"
          :closable="false"
          center
        >
        </el-alert>
      </div>
      <!--步骤条  -->
      <el-steps :active="activeIndex - 0" finish-status="success" simple>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 表单区域 -->
      <el-form
        ref="addFormRef"
        :model="addForm"
        label-width="100px"
        :rules="addFormRules"
      >
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="goodCategories"
                :props="cascaderProps"
                @change="handleChange"
                width="300px"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              v-for="item in goodManyList"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="v"
                  v-for="(v, i) in item.attr_vals"
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in goodOnlyList"
              :key="item.attr_id"
              :label="item.attr_name"
              label-width="180px"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              v-model="addForm.pics"
              drag
              :action="uploadURL"
              :headers="headerObj"
              multiple
              list-type="picture"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              style="width:100%;"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip"></div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor
              v-model="addForm.goods_introduce"
              style="height:280px"
            >
            </quill-editor>
            <!-- 添加商品的按钮 -->
            <el-button type="primary" class="btn-add" @click="clickAddGood"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewDialog"
      width="50%"
      :modal-append-to-body="false"
    >
      <img :src="previewPath" alt="" class="previewImg" />
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'
import baseURL from '@/utils/env.js'
import { getStorageItem } from '@/utils/auth'
import { getGoodCategories, getGoodCateList, addGood } from '@/api/goods'
export default {
  name: 'AddGood',
  data() {
    return {
      type: '',
      uploadURL: baseURL + 'upload',
      headerObj: {
        Authorization: getStorageItem('token')
      }, // 文件上传头
      previewDialog: false, // 预览图片的对话框
      previewPath: '', // 查看图片的路径
      addForm: {
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        // 商品所属的分类数组
        goods_cat: [],
        // 图片的数组
        pics: [],
        // 商品的详情描述
        goods_introduce: '',
        // 商品的参数（数组），包含 `动态参数` 和 `静态属性`
        attrs: []
      },
      activeIndex: 0,
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      goodCategories: [], // 商品分类列表
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          {
            required: true,
            message: '请选择商品分类'
          }
        ]
      },
      goodOnlyList: [], // 静态参数
      goodManyList: [] // 动态参数
    }
  },
  methods: {
    // 点击添加商品
    clickAddGood() {
      console.log(this.addForm)
      this.$refs.addFormRef.validate(valid => {
        if (!valid) {
          return this.$message.error('请填写必要的数据')
        }
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        this.goodManyList.forEach(v => {
          const attr = {
            attr_id: v.attr_id,
            attr_value: v.attr_vals.join(' ')
          }
          this.addForm.attrs.push(attr)
        })
        this.goodOnlyList.forEach(v => {
          const attr = {
            attr_id: v.attr_id,
            attr_value: v.attr_vals
          }
          this.addForm.attrs.push(attr)
        })
        form.attrs = this.addForm.attrs
        addGood(form).then(() => {
          this.$router.push('/goodlist')
        })
      })
    },
    // 文件上传成功
    handleSuccess(res) {
      const file = { pic: res.data.tmp_path }
      this.addForm.pics.push(file)
    },
    // 点击列表图片
    handlePreview(file) {
      console.log(file)
      this.previewPath = file.response.data.url
      this.previewDialog = true
    },
    handleRemove(file) {
      const delUrl = file.response.data.tmp_path
      const i = this.addForm.pics.findIndex(v => v.pic === delUrl)
      this.addForm.pics.splice(i, 1)
    },
    // 点击tabs标签触发
    async tabClicked() {
      if (this.activeIndex - 0 === 1) {
        // 动态参数
        const res = await this.getGoodCateList(
          this.addForm.goods_cat[2],
          'many'
        )
        res.forEach(v => {
          v.attr_vals
            ? (v.attr_vals = v.attr_vals.split(','))
            : (v.attr_vals = [])
        })
        this.goodManyList = res
      } else if (this.activeIndex - 0 === 2) {
        const res = await this.getGoodCateList(
          this.addForm.goods_cat[2],
          'only'
        )
        console.log(res)
        this.goodOnlyList = res
      }
    },
    async getGoodCateList(id, sel) {
      const { data: res } = await getGoodCateList({
        id,
        sel
      })
      return res
    },
    // 当tab栏发生变化的时候
    beforeTabLeave(activeName, oldActiveName) {
      // if (oldActiveName - 0 === 0) {
      //   if (this.addForm.goods_cat.length !== 3) {
      //     this.$message.error('请先选择商品分类')
      //     return false
      //   } else {
      //     this.$refs.addFormRef.validate(valid => {
      //       if (!valid) {
      //         this.$message.error('请填写所有需要填写的选项')
      //         return false
      //       }
      //     })
      //   }
      // }
    },
    async getGoodCategories() {
      const { data: res } = await getGoodCategories()
      this.goodCategories = res
    },
    handleChange() {
      // 级联选择器选项变化触发
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
        this.$message.error('请选择三级分类')
      }
    }
  },
  created() {
    const params = this.$route.params
    this.type = params.type
    if (params.type === 'edit') {
      console.log(params.data)
      this.addForm = params.data
    }
    this.getGoodCategories()
  }
}
</script>
<style lang="scss" scoped>
.el-form {
  margin-top: 20px;
  .el-tabs {
    .el-tabs__item {
      margin: 10px 0;
      font-size: 18px;
    }
    .el-cascader {
      width: 400px;
    }
  }
  .el-upload,
  .el-upload--picture {
    box-sizing: border-box;
    width: 100% !important;
    .el-upload-dragger {
      width: 100% !important;
      height: 180px;
    }
  }
}
.previewImg {
  width: 100%;
}
.btn-add {
  margin-top: 100px;
  width: 100%;
  height: 50px;
}
</style>
